import threading
import time

g_num = 0
def test1(temp):
    global g_num
    
    # 上锁，如果之前没有上过锁，那么此时上锁成功
    # 如果之前已经上过锁，堵塞，等待这个锁被解开，然后上锁
    mutex.acquire()
    for i in range(temp):

        g_num += 1
        mutex.release()

    # 解锁
    mutex.release()
    
    print('__test1  %s' % g_num)

def test2(temp):  
    global g_num
    
    mutex.acquire()
    for i in range(temp):
        g_num += 1

    mutex.release()
    print('__test2  %s' % g_num)
    
#  创建互斥锁，默认是没有上锁的
mutex = threading.Lock()

def main():

    t1 = threading.Thread(target=test1,args=(10000,)) #  如果是次数更多的话，结果
                                                    #  差距更大
    t2 = threading.Thread(target=test2,args=(10000,))
    t1.start()
    t2.start()

    time.sleep(2)
    print('__main  %s' % g_num)
if __name__ == '__main__':
    main()
